package com.service.purchase;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.http.impl.conn.ProxySelectorRoutePlanner;
import org.aspectj.weaver.patterns.HasMemberTypePatternForPerThisMatching;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.druid.filter.AutoLoad;
import com.alibaba.excel.EasyExcel;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.common.model.Global;
import com.common.spring.SpringMvcUtils;
import com.dao.purchase.AgreeDao;
import com.dao.purchase.OrderDao;
import com.dao.purchase.PlanMmMapper;
import com.dao.purchase.PurchaseMapper;
import com.dao.purchase.SupplyDealMapper;
import com.dao.purchase.SupplyDealMmMapper;
import com.enums.ContractTypeEnum;
import com.enums.WorkFlowIdModel;
import com.model.purchase.AgreeModel;
import com.model.purchase.OrderModel;
import com.model.purchase.PurchaseInquiryResult;
import com.model.purchase.PurchasePlanMm;
import com.model.purchase.PurchaseSupplyDeal;
import com.model.purchase.PurchaseSupplyDealMm;
import com.model.purchase.PurchaseSupplyDealVoModel;
import com.model.purchase.PurchaseSupplyOfferMm;
import com.model.supply.SupplyUserModel;
import com.model.sys.SysUser;
import com.service.external.sap.SapPurchaseService;
import com.service.external.zkh.ZKHService;

@Service
public class AgreeService {
	static final Logger logger = LoggerFactory.getLogger(AgreeService.class);

	@Autowired
	PlanMmMapper planMapper;
	@Autowired
	SupplyDealMapper supplyDealMapper;
	@Autowired
	SupplyDealMmMapper supplyDealMmMapper;
	@Autowired
	PurchaseMapper purchaseMapper;

	@Autowired
	SapPurchaseService sapPurchaseService;
	@Autowired
	ZKHService zkhService;
	@Autowired
	OrderDao orderDao;
	@Autowired
	CommonService commonService;

	/**
	 * 列表查询
	 *
	 * @param queryMap
	 * @return
	 */
	public HttpResult selectList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		queryMap.put("isContract", Global.MINUS_ONE + "");
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				if (StringUtils.isNotNull(sysUser.getBtnPermission())) {
					if (sysUser.getBtnPermission().contains(ContractTypeEnum.zkh.getValue())) {
						String[] strings = new String[1];
						strings[0] = ContractTypeEnum.zkh.getValue();
						queryMap.put("deptIds", strings);
						queryMap.put("zkhUserId", sysUser.getUserid());
					} else {
						queryMap.put("createId", sysUser.getUserid());
					}
				} else {
					queryMap.put("createId", sysUser.getUserid());
				}
			}
		}
		List<PurchaseSupplyDeal> list = supplyDealMapper.selectList(queryMap);
		int count = supplyDealMapper.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	/**
	 * 查询报价明细列表
	 *
	 * @param map
	 * @return
	 */
	public HttpResult selectMmList(String resId, String infId) {
		List<PurchaseSupplyDealMm> purchaseSupplyOfferMms = supplyDealMmMapper.loadByInfIdAndResId(resId, infId);
		HttpResult httpResult = new HttpResult();
		httpResult.setRows(purchaseSupplyOfferMms);
		return httpResult;
	}

	/**
	 * 详情
	 * 
	 * @param
	 * @return
	 */
	public HttpResult selectInfor(String resId, String infId) {
		HttpResult httpResult = new HttpResult();
		PurchaseSupplyDeal agreeModel = supplyDealMapper.load(resId, infId);
		PurchaseSupplyDealVoModel supplyDealVoModel = new PurchaseSupplyDealVoModel();
		BeanUtils.copyProperties(agreeModel, supplyDealVoModel);
		List<PurchaseSupplyDealMm> purchaseSupplyOfferMms = supplyDealMmMapper.loadByInfIdAndResId(resId, infId);
		supplyDealVoModel.setSupplyDealMms(purchaseSupplyOfferMms);
		httpResult.setData(supplyDealVoModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 保存
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult save(PurchaseSupplyDealVoModel agreeModel) {
		if (agreeModel == null || agreeModel.getSupplyDealMms() == null) {
			return HttpResult.error("参数不能为空");
		}
		SysUser sysUser = SpringMvcUtils.getSysUser();
		HttpResult httpResult = new HttpResult();
		int result = 0;
		agreeModel.setInqIsContract(Global.MINUS_ONE + "");
		agreeModel.setInqGroup(sysUser.getSap());
		String resIdString = agreeModel.getResId();
		if (!StringUtils.isNotNull(resIdString)) {
			String idString = UUID.randomUUID().toString();
			agreeModel.setResId(idString);
			agreeModel.setInqId(commonService.createCodeSap("purchase_supply_deal", "inq_id"));
		}

		agreeModel.setDealIsCheck(Global.YES + "");
		if (supplyDealMapper.update(agreeModel) == 0) {
			result += supplyDealMapper.insert(agreeModel);
		} else {
			result++;
		}

		for (PurchaseSupplyDealMm supplyDealMm : agreeModel.getSupplyDealMms()) {
			supplyDealMm.setInfId(agreeModel.getInfId());
			supplyDealMm.setInfCode(agreeModel.getInfCode());
			supplyDealMm.setInfName(agreeModel.getInfName());
			supplyDealMm.setResId(agreeModel.getResId());
			supplyDealMm.setGramId(agreeModel.getGramId());
			if (supplyDealMmMapper.update(supplyDealMm) == 0) {
				result += supplyDealMmMapper.insert(supplyDealMm);
			} else {
				result++;
			}
			// 采购计划数量超出时，状态改为2
			PurchasePlanMm planMm = planMapper.load(supplyDealMm.getPlanId());
			BigDecimal sumDecimal = purchaseMapper.getAgreeSum(supplyDealMm.getPlanId());
//			if (planMm.getPlanPurNum().compareTo(sumDecimal) < 0) {
//				return HttpResult.error(planMm.getPlanId() + "---该协议订单采购量已用完，请重新提报需求计划");
//			}
			BigDecimal stockDecimal = new BigDecimal(0);
			if (sumDecimal != null) {
				stockDecimal = planMm.getPlanPurNum().subtract(sumDecimal);
			}
			if (supplyDealMm.getDealNum() != null) {
				stockDecimal = planMm.getPlanPurNum().subtract(supplyDealMm.getDealNum());
			}
			if (stockDecimal.compareTo(BigDecimal.ZERO) <= 0) {
				planMm.setStatus(Global.NUMERICAL_TWO + "");
			} else {
				planMm.setStatus(Global.YES + "");
			}
//			planMm.setStatus(Global.NUMERICAL_TWO + "");
			planMm.setPlanStockNum(stockDecimal);
			planMapper.update(planMm);
		}

		// 提交时sap订单生效
		if (agreeModel.getStatus().equals(Global.YES + "")) {
			// 生成采购订单
			OrderModel orderModel = new OrderModel();
			orderModel.setOrdId(agreeModel.getResId());

			orderModel.setResId(agreeModel.getResId());
			orderModel.setInfId(agreeModel.getInfId());
			orderModel.setInfCode(agreeModel.getInfCode());
			orderModel.setInfName(agreeModel.getInfName());
			orderModel.setOrdFreight(agreeModel.getInfLastTotalPrice());
			orderModel.setResName(agreeModel.getInqName());
			orderModel.setOrdName(agreeModel.getInqName());
			orderModel.setOrdContractName(agreeModel.getInfContact());
			orderModel.setOrdIsSign(Global.NO + "");
			orderDao.insert(orderModel);
//			// 调用sap接口创建采购订单
//			HttpResult sapHttpResult = sapPurchaseService.createSapOrder(agreeModel, orderModel);
//
//			if (sapHttpResult.getCode() == HttpStatus.SUCCESS_CODE) {
//				orderModel.setOrdCode(sapHttpResult.getData().toString());
//				if (orderDao.update(orderModel) == 0) {
//					result += orderDao.insert(orderModel);
//				}
//			} else {
//				return HttpResult.error("sap返回：" + sapHttpResult.getMsg());
//			}
//
//			sapHttpResult = sapPurchaseService.changeSapOrderStatus(agreeModel.getGramId());
//			if (sapHttpResult.getCode() != HttpStatus.SUCCESS_CODE) {
//				return HttpResult.error(sapHttpResult.getMsg());
//			} else {
//				// 修改sap状态
//				agreeModel.setInqSapStatus(Global.YES + "");
//				result += supplyDealMapper.update(agreeModel);
//				// 调用震坤行接口
//				zkhService.addZkhOrder(agreeModel.getGramId());
//			}
//			// 调用震坤行接口
//			HttpResult zkHttpResult = zkhService.addZkhOrder(agreeModel.getInqId());
//			if (zkHttpResult.getCode() != HttpStatus.SUCCESS_CODE) {
//				// 强制手动事务回滚
//				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//				return HttpResult.error(zkHttpResult.getMsg());
//			}
		}

		if (result > 0) {
			httpResult.setMsg(agreeModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(agreeModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(agreeModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * 删除
	 *
	 * @param
	 * @return
	 */
	public HttpResult deleteByResIdInfId(String resId, String infId) {
		if (!StringUtils.isNotNull(resId)) {
			return HttpResult.error("参数不能为空");
		}
		PurchaseSupplyDeal model = supplyDealMapper.load(resId, infId);
		if (!model.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("非待提交状态，不可删除！");
		}

		HttpResult httpResult = new HttpResult();
		int result = supplyDealMapper.delete(resId, infId);
		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 退回
	 * 
	 * @param purchasePlanMm
	 * @return
	 */
	@Transactional
	public HttpResult back(String resId) {
		if (resId == null) {
			return HttpResult.error("请求参数不能为空!");
		}
		List<PurchaseSupplyDeal> supplyDeal = supplyDealMapper.loadByResId(resId);
		if (supplyDeal == null) {
			return HttpResult.error("不存在此条数据！");
		}
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("status", Global.NO + "");
		hashMap.put("resId", resId);
		List<OrderModel> orderModel = orderDao.selectList(hashMap);
		if (orderModel != null && orderModel.size() == 0) {
			return HttpResult.error("订单已生成，不可撤回！");
		}
		orderDao.delete(orderModel.get(0).getOrdId());
		List<PurchaseSupplyDealMm> purchaseSupplyOfferMms = supplyDealMmMapper.loadByResId(resId);
		for (PurchaseSupplyDealMm supplyDealMm : purchaseSupplyOfferMms) {
			PurchasePlanMm planMm = planMapper.load(supplyDealMm.getPlanId());
			if (planMm.getPlanStockNum() != null && supplyDealMm.getDealNum() != null) {
				planMm.setPlanStockNum(planMm.getPlanStockNum().add(supplyDealMm.getDealNum()));
			}
			planMapper.update(planMm);
		}

		int result = 0;
		supplyDeal.get(0).setStatus(Global.NO + "");
		result = supplyDealMapper.update(supplyDeal.get(0));
		if (result > 0) {
			return HttpResult.ok("回退成功");
		} else {
			return HttpResult.error("不存在此询价结果!");
		}
	}

	@Transactional
	public HttpResult delete(String resId, String infId) {
		if (!StringUtils.isNotNull(resId)) {
			return HttpResult.error("参数不能为空");
		}

		PurchaseSupplyDeal model = supplyDealMapper.load(resId, infId);
		if (!model.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("非待提交状态，不可删除！");
		}

		HttpResult httpResult = new HttpResult();
		int result = 0;
		List<PurchaseSupplyDealMm> purchaseSupplyOfferMms = supplyDealMmMapper.loadByResId(resId);
		for (Iterator iterator = purchaseSupplyOfferMms.iterator(); iterator.hasNext();) {
			PurchaseSupplyDealMm purchaseSupplyDealMm = (PurchaseSupplyDealMm) iterator.next();
			PurchasePlanMm plan = planMapper.load(purchaseSupplyDealMm.getPlanId());
			plan.setStatus(Global.YES + "");
			planMapper.update(plan);
		}
		result += supplyDealMapper.deleteByResId(resId);
		result += supplyDealMmMapper.deleteByResId(resId);

		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 导出
	 * 
	 * @param queryMap
	 * @param response
	 */
	public void export(Map<String, Object> queryMap, HttpServletResponse response) {
		queryMap.put("isContract", Global.MINUS_ONE + "");
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				if (StringUtils.isNotNull(sysUser.getBtnPermission())) {
					if (sysUser.getBtnPermission().contains(ContractTypeEnum.zkh.getValue())) {
						String[] strings = new String[1];
						strings[0] = ContractTypeEnum.zkh.getValue();
						queryMap.put("deptIds", strings);
						queryMap.put("zkhUserId", sysUser.getUserid());
					} else {
						queryMap.put("createId", sysUser.getUserid());
					}
				} else {
					queryMap.put("createId", sysUser.getUserid());
				}
			}
		}
		List<PurchaseSupplyDeal> list = supplyDealMapper.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), AgreeModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}
}
